using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Locations;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.Util;
using Tracker.Mobile.Droid.TrackerWebService;

namespace Tracker.Mobile.Droid.Tasks
{
    public class LocationTask : TimerTask
    {
        private readonly Context _context;
        private readonly Geocoder _geocoder;
        private readonly LocationManager _locationManager;
        private readonly TrackerService _webService;
        private readonly ISharedPreferences _preferences;

        private Location _location;

        public LocationTask(Context context)
        {
            _context = context;
            _geocoder = new Geocoder(_context);
            _locationManager = _context.GetSystemService(Context.LocationService) as LocationManager;
            _webService = new TrackerService();
            _preferences = _context.GetSharedPreferences(Global.Preferences, FileCreationMode.Private);
        }

        public override void Run()
        {
            _location = _locationManager.GetLastKnownLocation(LocationManager.GpsProvider);

            if (_location == null)
            {
                _location = _locationManager.GetLastKnownLocation(LocationManager.NetworkProvider);
            }

            if (_location != null)
            {
                TrackPosition();
            }
        }

        private void TrackPosition()
        {
            int userID = _preferences.GetInt(PreferenceKeys.UserID, 1);
            var addresses = _geocoder.GetFromLocation(_location.Latitude, _location.Longitude, 1);
            PositionDTO position = new PositionDTO();

            position.UserID = userID;
            position.Latitude = _location.Latitude;
            position.Longitude = _location.Longitude;

            if (addresses != null && addresses.Count > 0)
            {
                var address = addresses[0];

                position.Address1 = address.GetAddressLine(0);
                position.City = address.Locality;
                position.State = address.AdminArea;
                position.Zip = address.PostalCode;
            }

            _webService.TrackPosition(position);

            Intent locationUpdate = new Intent();
            locationUpdate.SetAction("LocationUpdate");
            _context.SendBroadcast(locationUpdate);
        }
    }
}